package com.mop.app.global;

import com.mop.app.common.enums.AppBizEnums;
import com.mop.app.common.exception.BizException;
import com.mop.app.common.exception.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Resource;

/**
 * 全局控制器异常捕获
 *
 * @author wchen
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    @ExceptionHandler(value = BizException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Message handler(BizException ex) {
        logger.error("error:", ex);
        return Message.error(ex.getCode(), ex.getMsg());
    }

    /**
     * 参数校验不通过后的统一处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.OK)
    public Message argsNotValidExceptionHandle(MethodArgumentNotValidException e) {
        logger.error("参数校验不通过", e);
        String errorMessage = e.getBindingResult().getFieldError().getDefaultMessage();

        return Message.error(AppBizEnums.ERROR.getCode(), errorMessage);
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Message handler(Exception e) {
        logger.error("error:", e);
        return Message.error(AppBizEnums.ERROR.getCode(), AppBizEnums.ERROR_COMMON.getDesc());
    }
}
